package woa.stack;

import java.util.*;

/**
 * 二叉树的中序遍历
 * 给定一个二叉树的根节点 root ，返回它的 中序 遍历。
 * <p>
 * 输入：root = [1,null,2,3]
 * 输出：[1,3,2]
 *
 * @author wangpeng
 * @date 2021/11/30
 */
public class InorderTraversalProblem {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> rs = new ArrayList<>();
        if (root == null) {
            return rs;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        Set<TreeNode> visited = new HashSet<>();

        while (!stack.isEmpty()) {
            TreeNode cur = stack.peek();
            if (cur.left == null || visited.contains(cur.left)) {
                rs.add(cur.val);
                visited.add(cur);
                stack.pop();
                if (cur.right != null) {
                    stack.add(cur.right);
                }
            } else {
                stack.add(cur.left);
            }
        }
        return rs;
    }

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        System.out.println(inorderTraversal(node1));
    }
}
